package com.zzyl.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

@Component
@Slf4j
public class DingTalkClient {

    private static final String WEBHOOK = "https://oapi.dingtalk.com/robot/send?access_token=be2955a979606d90f7c98c6fb11949fc98ca703abd476d367e75fa357f1a1b21";
    private static final String SECRET = "SECdd93676e565c0f6e520547af368f50058f01e0981c20a3c809686de2f6175ffd";

    @Resource
    RestTemplate restTemplate;

    /**
     * 发送普通文本消息
     * @param msg 消息（携带的关键字）
     * @param isAtAll 是否@所有人
     * @param mobiles 通过手机号@群众某几个业务负责人
     */
    public void sendTextMsg(String msg, Boolean isAtAll, List<String> mobiles) {
        HashMap<String, Object> map = new HashMap<>();
        //先设置消息类型msgtype，发送普通文本消息
        map.put("msgtype", "text");
        //设置消息内容
        HashMap<String, Object> content = new HashMap<>();
        content.put("content", "业务告警"+msg);
        map.put("text", content);
        //设置群聊的@手机号
        HashMap<Object, Object> atMap = new HashMap<>();
        atMap.put("isAtAll", isAtAll);
        atMap.put("atMobiles", mobiles);
        map.put("at", atMap);
        ResponseEntity<String> response = restTemplate.postForEntity(getDingUrl(), map, String.class);
        log.info("请求结果{}",response.getBody());
    }

    public void sendLinkMsg(String url, String msg,String imageUrl) {
        HashMap<String, Object> map = new HashMap<>();
        //先设置消息类型msgtype，发送普通文本消息
        map.put("msgtype", "link");
        //设置消息内容
        HashMap<String, Object> content = new HashMap<>();
        content.put("messageUrl", url);
        content.put("title", "业务告警："+msg);
        content.put("picUrl", imageUrl);
        content.put("text", msg);
        map.put("link", content);
        ResponseEntity<String> response = restTemplate.postForEntity(getDingUrl(), map, String.class);
        log.info("",response.getBody());
    }
    private String getDingUrl() {
        String url = WEBHOOK;
        try {
            Long timestamp = System.currentTimeMillis();
            String stringToSign = timestamp + "\n" + SECRET;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(SECRET.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            return url + "&timestamp=" + timestamp + "&sign=" + sign;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取签名失败");
        }
    }
}
